<?php

namespace XWAM\Model;

/**
 * RuleModel类
 *
 * @since 1.0 <2015-10-19> SoChishun <14507247@qq.com> Added.
 */
class RuleModel extends AppbaseModel {

    protected $tableName = 'think_auth_rule';

    function select_tree($select_options = array(), $data_options = array()) {
        $select_options = array_merge(array('field' => 'id, title, pid, type, sort, status, create_time', 'order' => 'sort, id'), $select_options);
        return $this->base_get_tree_list($select_options, $data_options);
    }

    function select_json_tree($select_options = array(), $data_options = array()) {
        $select_options = array_merge(array('field' => 'id, title as text', 'order' => 'sort, id'), $select_options);
        return $this->base_get_tree_list($select_options, $data_options);
    }

    function save_rule() {
        $rules = array(
            array('title', 'require', '标题无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
        );
        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->error);
        }
        if (empty($this->id)) {
            $result = $this->add();
        } else {
            $result = $this->save();
        }
        return $this->returnMsg($result);
    }

    /**
     * 复制规则
     * @return type
     * @since 1.0 <2016-1-14> SoChishun Added.
     */
    function copy_rule($id) {
        $table = $this->tableName;
        M()->execute("insert into $table (title,pid,`code`,status) select concat(title,'_new'),pid,`code`,status from $table where id=$id");
        return $this->returnMsg(true);
    }

    function change_status($id, $status) {
        $result = $this->where(array('id' => $id))->setField(array('status' => $status));
        return $this->returnMsg($result);
    }

    function change_sort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return $this->returnMsg($result);
    }

    public function delete_rule($id = '') {
        if (!$id) {
            return $this->returnMsg(false, '参数无效');
        }
        // 判断是否有子项目
        $list = $this->query('select a.title from ' . $this->tableName . ' a inner join ' . $this->tableName . ' b on b.pid=a.id where b.pid in (' . $id . ')');
        $names = false;
        if ($list) {
            foreach ($list as $row) {
                $names.=',' . $row['name'];
            }
        }
        if ($names) {
            return $this->returnMsg(false, '请先转移下级规则:' . "\n" . ltrim($names, ','));
        }
        $result = $this->delete($id);
        return $this->returnMsg($result);
    }

    /**
     * 获取用户权限菜单
     * @return boolean
     */
    function get_menus() {
        if (user_check_login($login_data)) {
            $uid = $login_data['id'];
            $cache_key = 'menu_' . $uid;
            $data = S($cache_key);
            if ($data) {
                return $data;
            }
            /* 2016-4-6
              // 2016-2-17 $group_ids = $this->table(C('AUTH_CONFIG.AUTH_GROUP_ACCESS'))->where(array('uid' => $login_data['id']))->getField('group_id', true);
              $group_ids = $this->table('t_porg_user')->where(array('id' => $uid))->getField('role_ids'); // C('AUTH_CONFIG.AUTH_USER')
              if (!$group_ids) {
              return false;
              }
              // 2016-2-17 $rule_ids = $this->table(C('AUTH_CONFIG.AUTH_GROUP'))->where(array('group_id' => array('in', $group_ids)))->getField('rules', true);
              // 2016-2-17 $rule_ids = implode(',', $rule_ids);
              $rule_ids = $this->table('think_auth_group')->where(array('id' => array('in', $group_ids)))->getField('rules'); // C('AUTH_CONFIG.AUTH_GROUP')
             */
            $rule_ids = $this->table('think_auth_group')->where('id in (select role_ids from t_porg_user where id=' . $uid . ')')->getField('rules');
            if (!$rule_ids) {
                return false;
            }
            if (false !== strpos($rule_ids, '*')) {
                $rule_ids = '';
            }
            $data = $this->fn_get_menus(0, $rule_ids);
            S($cache_key, $data, 15);
            return $data;
        }
        return false;
    }

    /**
     * 加载菜单(辅助方法)
     * @param int $pid
     * @param array $rule_ids 权限编号
     * @return mixed
     * @since 1.0 <2014-6-19> sutroon Added.
     * @since 2.0 <2015-10-19> SoChishun Added.
     */
    function fn_get_menus($pid = 0, $rule_ids = array()) {
        $where = array('pid' => $pid, 'type' => 'M');
        if ($rule_ids) {
            $where['id'] = array('in', $rule_ids);
        }
        $list = $this->cache(3)->where($where)->field('id, name, title, code, addon, url')->select();
        if ($list) {
            foreach ($list as &$row) {
                $row['children'] = $this->fn_get_menus($row['id'], $rule_ids);
            }
        }
        return $list;
    }

    /**
     * 获取侧边栏菜单
     * @param type $code
     * @return boolean
     */
    function get_aside_menus($code) {
        $data = $this->get_menus();
        if ($data) {
            foreach ($data as $r) {
                if ($code == $r['code']) {
                    return $r['children'];
                }
            }
        }
        return false;
    }

    /**
     * 获取指定addon的侧边栏
     * @param type $addon
     * @return type
     */
    function get_aside_menus_by_addon($addon = '') {
        $code = $this->where(array('addon' => $addon, 'pid' => 0))->getField('code');
        return $this->get_aside_menus($code);
    }

    /**
     * 获取指定id的侧边栏
     * @param type $id
     * @return type
     * @since 1.0 <2016-3-10> SoChishun Added.
     */
    function get_aside_menus_by_id($id = 0) {
        $addon = $this->where(array('id' => $id))->getField('addon');
        $code = $this->where(array('addon' => $addon, 'pid' => 0))->getField('code');
        return $this->get_aside_menus($code);
    }

    /**
     * 获取历史访问菜单
     * @return boolean
     * @since 1.0 <2015-12-11> SoChishun Added.
     */
    function get_history_menus() {
        $name = 'MENU_HISTORY';
        $sids = cookie($name);
        if (!$sids) {
            return false;
        }
        $aout = $this->where(array('id' => array('in', $sids)))->field('id, title, url')->select();
        return $aout;
    }

    /**
     * 获取历史访问菜单
     * @return boolean
     * @since 1.0 <2015-12-11> SoChishun Added.
     */
    function get_history_menus2() {
        $name = 'menu_history';
        $sdata = cookie($name);
        if (!$sdata) {
            return false;
        }
        $adata = json_decode($sdata, true);
        if (!$adata) {
            return false;
        }
        $cur = $adata['cur'];
        $ids = $adata['ids'];
        $data = $this->get_menus();
        $out = array();
        foreach ($data as $r1) {
            if ($sub1 = $r1['children']) {
                foreach ($sub1 as $r2) {
                    if ($sub2 = $r2['children']) {
                        foreach ($sub2 as $r3) {
                            if (in_array($r3['id'], $ids)) {
                                $r3['active'] = $cur == $r3['id'];
                                $out[] = $r3;
                            }
                        }
                    }
                }
            }
        }
        return $out;
    }

}
